package com.spring.boot.service.impl;

import com.spring.boot.dao.AreaDao;
import com.spring.boot.entity.Area;
import com.spring.boot.service.AreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 *
 * @author zhengzihong
 * @date 2018/2/23
 */
@Service
public class AreaServiceImpl implements AreaService {
    @Autowired
    private AreaDao areaDao;

    @Override
    public List<Area> queryArea() {
        return areaDao.queryArea();
    }

    @Override
    public Area queryAreaById(int areaId) {
        return areaDao.queryAreaById(areaId);
    }

    /**
     * 添加事务回滚
     *
     * @param area
     * @return
     */
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public boolean insertArea(Area area) {
        if (area != null && area.getAreaName() != null && !"".equals(area.getAreaName())) {
            Date now = new Date();
            area.setCreateTime(now);
            area.setLastEditTime(now);
            try {
                int effectedNum = areaDao.insertArea(area);
                if (effectedNum > 0) {
                    return true;
                } else {
                    throw new RuntimeException("插入地域信息失败");
                }
            } catch (Exception e) {
                throw new RuntimeException("插入地域信息失败:" + e.getMessage());
            }
        } else {
            throw new RuntimeException("插入地域信息不能为空");
        }
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean updateArea(Area area) {
        if (area != null && area.getAreaId() != null) {
            Date now = new Date();
            area.setLastEditTime(now);
            try {
                int effectedNum = areaDao.updateArea(area);
                if (effectedNum > 0) {
                    return true;
                } else {
                    throw new RuntimeException("更新区域信息失败");
                }
            } catch (Exception e) {
                throw new RuntimeException("更新区域信息失败:" + e.getMessage());
            }
        } else {
            throw new RuntimeException("更新区域信息不能为空");
        }
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean deleteArea(int areaId) {
        if (areaId > 0) {
            try {
                int effectNum = areaDao.deleteArea(areaId);
                if (effectNum > 0) {
                    return true;
                } else {
                    throw new RuntimeException("区域信息删除失败");
                }
            } catch (Exception e) {
                throw new RuntimeException("区域信息删除失败:" + e.getMessage());
            }
        }
        throw new RuntimeException("区域信息Id必须大于0");
    }
}
